<?php

namespace App\Models;

use Illuminate\Support\Facades\DB;

class Recharge extends Base
{
    //获取充值记录
    public function getPageList($options=[],$where=[],$whereDates){
        try{
            $limit = (isset($options['limit']) && $options['limit']) ? $options['limit'] : 1;
            $page = (isset($options['page']) && $options['page']) ? $options['page'] : 1;
            $model = $this->leftJoin('users','users.id','=','recharges.uid');
            if(!empty($whereDates)){
                $model = $model->whereDate('recharges.created_at','>=',$whereDates[0])->whereDate('recharges.created_at','<',$whereDates[1]);
            }
            $model=$model->select('recharges.*','users.username','users.email','users.contact','users.total','users.username_zn')
                ->where($where)->orderBy('recharges.created_at','desc');
            $result = $this->paging($model,$page,$limit);
            return $result;
        }catch (\Exception $e){
            return [
                'code'=>1,
                'message'=>$e->getMessage()
            ];
        }
    }

    //充值审核
    public function examine($data){
        try {
            $recharge = self::find($data['id']);
            if(!$recharge){
                return [
                    'code'=>1,
                    'message'=>'充值单不存在'
                ];
            }
            $transition = (new Transition())->where([
                'orderid'=>$data['id'],
                'transtype'=>4,
                'uid'=>$recharge->uid
            ])->first();
            if(!$transition){
                return [
                    'code'=>1,
                    'message'=>'交易单不存在'
                ];
            }
            if($transition->status==2){
                return [
                    'code'=>1,
                    'message'=>'交易单已成功支付'
                ];
            }
            $recharge->status = $data['status'];
            $user = User::find($recharge->uid);
            if($data['status']==2){ //审核成功
                $transition->status = 2;
                $user->balance += $transition->number;
            }else{
                $transition->status = 4;
            }
            DB::transaction(function ()use ($recharge,$user,$transition){
                $recharge->save();
                $transition->save();
                $user->save();
            },5);
            return [
                'code'=>0,
                'data'=>''
            ];
        }catch (\Exception $e){
            return [
                'code'=>1,
                'message'=>$e->getMessage()
            ];
        }
    }
}
